package com.javatimes.test.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.springframework.util.StringUtils;

public class JsonUtils extends Struts2Utils {

	// Spring容器初始化组件注入JSON配置对象
	private JsonConfig config;//json自带的类型

	private static JsonUtils jsonUtils;

	// spring容器初始化执行
	public void init() {
		jsonUtils = this;
		jsonUtils.config = this.config;
	}

	//dwr() jquery ext  返回数据  
	// action请求数据到JSON list<map>  list<dept> //json ssh  strust配制  spring
	public static final void toJsonToWeb(Object data) {
		HttpServletResponse response = initResponseHeader("application/json");///ajax  setHeader
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		try {
			JSON json = JSONSerializer.toJSON(data, jsonUtils.config);///生成json数据格式(有数据吗?!) data (List<dept>转成json)
			PrintWriter pw = response.getWriter();//pr
			json.write(pw);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 过滤JSON数据不包括哪些字段 例如： String json = {a : "1" , b: "2" , c : "3"};
	 * jsonExcludes("a,b"); 输出 {c:3};
	 * 
	 * @param exclude
	 */
	public static final void jsonExcludes(String exclude) {
		String[] excludes = StringUtils
				.delimitedListToStringArray(exclude, ",");
		if (null != exclude && null != excludes) {
			jsonUtils.config.setExcludes(excludes);
		}
	}

	/**
	 * 过滤JSON数据包括哪些字段 例如： String json = {a : "1" , b: "2" , c : "3"};
	 * jsonIncludes("a,b"); 输出 {a : "1" , b: "2"};
	 * 
	 * @param include
	 */
	public static final void jsonIncludes(String include) {
		final String[] includes = StringUtils.delimitedListToStringArray(
				include, ",");
		if (null != include && null != includes) {
			// 声明JSON属性过滤器
			PropertyFilter filter = new PropertyFilter() {
				public boolean apply(Object source, String name, Object value) {
					for (int i = 0; i < includes.length; i++) {
						if (name.equals(includes[i]))
							return false; // 返回 false, 表示这个属性将保留
					}
					return true; // 返回 true, 表示这个属性将被过滤掉
				}
			};
			jsonUtils.config.setJsonPropertyFilter(filter);
		}
	}

	public JsonConfig getConfig() {
		return config;
	}

	public void setConfig(JsonConfig config) {
		this.config = config;
	}

	public static JsonUtils getJsonUtils() {
		return jsonUtils;
	}

	public static void setJsonUtils(JsonUtils jsonUtils) {
		JsonUtils.jsonUtils = jsonUtils;
	}
	
}
